layui.define([], function (exports) {
    var layer = layui.layer,
        form = layui.form,
        table = layui.table,
        render = function (GUID, roots, pager, initSort) {
            roots.find('.layui-form').each(function () {
                form.render(null, $(this));
            });
            roots.find('.shForm').submit(function () {
                var searchData = $(this).find(':input').serialize(),
                    localArea = jdiyAdmin.getLocalArea(roots).attr('searchData', searchData);
                jdiyAdmin.load(localArea, null, searchData);
                return false;
            });
            roots.find('.shForm .export').click(function () {
                let action = jdiyAdmin.util.url(jdiyAdmin.ctx + '/mgmt/' + $(this).attr('action'));

                /*20210816 zlt fixed:
                以下try..catch的作用是获取当前list列表界面的url参数，并设置到导出action地址*/
                /*如果list界面url中有参数，导出时同样要带入，否则导出可能报错．*/
                try {
                    let thisListUrl = $(this).parents('.localRefresh').first().data('url'),
                        iw = thisListUrl.indexOf('?');
                    if (iw > -1) action.set(thisListUrl.substring(iw + 1));
                } catch (e) {
                }/*===================+*/

                var fm = $('<form method="post" target="_blank"></form>')
                    .attr('action', action.toString())
                    .appendTo('body');
                $("input, textarea,select", $(this).parents('form').first()).each(function () {
                    fm.append('<textarea name="' + this.name + '">' + this.value + '</textarea>');
                });
                fm.submit();
                fm.remove();
            });

            if (pager) {
                var prms = {autoSort: false, defaultToolbar: [], limit: pager.thisCount},
                    tools = $('#toolbar' + GUID);
                if (tools.length) prms.toolbar = '#toolbar' + GUID;
                if (initSort && initSort.field) prms.initSort = initSort;
                table.init('table' + GUID, prms);
                table.on('rowDouble(table' + GUID + ')', function (obj) {
                    $(obj.tr).find('.dblclick').click();
                });
                table.on('row(table' + GUID + ')', function (obj) {
                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//标注选中样式
                });
                table.on('sort(table' + GUID + ')', function (obj) {
                    //console.log(obj.field); //当前排序的字段名
                    //console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
                    //console.log(this); //当前排序的 th 对象
                    if ('asc' === obj.type || 'desc' === obj.type) {
                        roots.find('.shForm input[name=orderField]').val(obj.field);
                        roots.find('.shForm input[name=orderDirection]').val(obj.type);
                    } else {
                        roots.find('.shForm input[name=orderField]').val('');
                        roots.find('.shForm input[name=orderDirection]').val('');
                    }
                    var searchData = (roots.find('.shForm :input').serialize() || '1=1')
                        + '&page=1&pageSize=' + pager.pageSize,
                        localArea = jdiyAdmin.getLocalArea(roots).attr('searchData', searchData);
                    jdiyAdmin.load(localArea, null, searchData);
                });


                layui.laypage.render({
                    elem: 'pager' + GUID, //注意，这里的 test1 是 ID，不用加 # 号
                    layout: ['prev', 'page', 'next', 'limit', 'count', 'skip'],
                    limit: pager.pageSize,
                    limits: [5, 10, 12, 15, 20, 30, 50, 100, 200],
                    curr: pager.page,
                    count: pager.rowCount,
                    jump: function (obj, first) {
                        //obj包含了当前分页的所有参数，比如：
                        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        //console.log(obj.limit); //得到每页显示的条数
                        //首次不执行
                        if (!first) {
                            var searchData = (roots.find('.shForm :input').serialize() || '1=1')
                                + '&page=' + obj.curr + '&pageSize=' + obj.limit,
                                localArea = jdiyAdmin.getLocalArea(roots).attr('searchData', searchData);
                            jdiyAdmin.load(localArea, null, searchData);
                        }
                    }
                });
            }
        },
        exec = function (GUID, pager, iniSort) {
            let roots = $('#body' + GUID);
            render(GUID, roots, pager, iniSort);
            /*这儿直接添加事件html属性了,防止列表管理界面，管理列宽度不够会被LayUI自动弄个弹层显示控制按钮，弹层出来的无事件。*/
            roots.find('a[target=ajaxTodo],button[target=ajaxTodo]').attr('onclick', 'jdiyAdmin.got.ajaxTodo(this,\'body' + GUID + '\');return false;');
            roots.find('a[target=dialog],button[target=dialog]').attr('onclick', 'jdiyAdmin.got.dialog(this,\'body' + GUID + '\');return false;');
            roots.find('a[target=tab],button[target=tab]').attr('onclick', 'jdiyAdmin.got.tab(this,\'body' + GUID + '\');return false;');
            roots.find('.localRefresh').each(function () {
                let oThis = $(this);
                jdiyAdmin.load(oThis);
                /*JDiy20210901:下行，没有id,加一个唯一id,用于处理opener的刷新问题*/
                if (!oThis.attr('id')) oThis.attr('id', 'localRefresh' + jdiyAdmin.util.nextInt++);
            });

            roots.find('a[target=bat_ajaxTodo]').click(function () {
                var tb = roots.find('.layui-table').attr('lay-filter'),
                    checkStatus = layui.table.checkStatus(tb), idsa = [], ids;
                if (checkStatus.data.length === 0) {
                    layer.msg("请先打钩选择要操作的数据行！");
                    return false;
                }
                let fv;
                for (let i = 0; i < checkStatus.data.length; i++) {
                    fv = checkStatus.data[i].id || checkStatus.data[i]._id_ || false;
                    if (fv) idsa.push(fv);
                }
                if (idsa.length === 0) {
                    layer.msg("获取选中数据id失败，请确认id字段是否出现在数据表格中！");
                    return false;
                }
                ids = 'id=' + idsa.join('&id=');

                let confirm = $(this).attr('confirm'),
                    href = $(this).attr('href'),
                    http = function () {
                        var loading = layer.load(0);
                        $.ajax({
                            url: href,
                            data: ids,
                            success: function (ret) {
                                layer.close(loading);
                                jdiyAdmin.ajaxDone(ret);
                                if (ret.code === 200) {
                                    let localArea = jdiyAdmin.getLocalArea(roots);
                                    jdiyAdmin.load(localArea, null, localArea.attr('searchData'));

                                    /*jdiy20210901:以下代码，判断如果当前列表界面是由其它界面弹出的，则ajax执行后，也把它的opener刷新*/

                                    let opener = localArea.attr('opener');
                                    if (opener && opener !== '') {
                                        let openerArea = jdiyAdmin.getLocalArea($('#' + opener));
                                        jdiyAdmin.load(openerArea, null, openerArea.attr('searchData'));
                                    }
                                    //================================================================================
                                }
                            },
                            error: function (jqXHR) {
                                layer.close(loading);
                                layer.alert(jqXHR.responseText, {
                                    icon: 2,
                                    title: '操作失败,返回错误:'
                                });
                            }
                        });
                    };
                if (confirm && confirm !== '') {
                    layer.confirm(confirm, function (index) {
                        layer.close(index);
                        http();
                    });
                } else http();
                return false;
            }).removeAttr('target');
            roots.find('a[target=bat_edit]').click(function () {
                let width = parseInt($(this).attr('width')) || 700,
                    height = parseInt($(this).attr('height')) || 450,
                    href = $(this).attr('href'),
                    title = $(this).attr('title') || $(this).text(),
                    tb = roots.find('.layui-table').attr('lay-filter'),
                    checkStatus = layui.table.checkStatus(tb), idsa = [], ids;
                if (checkStatus.data.length === 0) {
                    layer.msg("请先打钩选择要操作的数据行！");
                    return false;
                }
                let fv;
                for (let i = 0; i < checkStatus.data.length; i++) {
                    fv = checkStatus.data[i].id || checkStatus.data[i]._id_ || false;
                    if (fv) idsa.push(fv);
                }
                if (idsa.length === 0) {
                    layer.msg("获取选中数据id失败，请确认id字段是否出现在数据表格中！");
                    return false;
                }

                layer.open({
                    type: 8
                    , title: title
                    , content: jdiyAdmin.util.url(href).set('_ids', idsa.join(',')).toString()
                    , opener: jdiyAdmin.getLocalArea($(this)).attr('id')
                    , maxmin: true
                    , area: [width + 'px', height + 'px']
                    , btn: ['确定', '取消']
                    , yes: function (index, layero) {
                        //点击确认触发 iframe 内容中的按钮提交
                        layero.find("button[type=submit]").click();
                    }
                });
                return false;
            });

            roots.find('a[target=bat_blank]').click(function () {
                let href = $(this).attr('href'),
                    tb = roots.find('.layui-table').attr('lay-filter'),
                    checkStatus = layui.table.checkStatus(tb), idsa = [];
                if (checkStatus.data.length === 0) {
                    layer.msg("请先打钩选择要操作的数据行！");
                    return false;
                }
                let fv;
                for (let i = 0; i < checkStatus.data.length; i++) {
                    fv = checkStatus.data[i].id || checkStatus.data[i]._id_ || false;
                    if (fv) idsa.push('<input type="hidden" name="id" value="'+fv+'"/>');
                }
                if (idsa.length === 0) {
                    layer.msg("获取选中数据id失败，请确认id字段是否出现在数据表格中！");
                    return false;
                }
                var fm = $('<form method="post" target="_blank"></form>')
                    .attr('action', href)
                    .appendTo('body');
                fm.append(idsa.join(""));
                fm.submit();
                fm.remove();
                return false;
            });


            roots.find('input[target=lookup]').click(function () {
                var width = parseInt($(this).attr('width')) || 480,
                    height = parseInt($(this).attr('height')) || 300,
                    href = jdiyAdmin.util.url($(this).attr('href')).set('value', this.value).toString(),
                    title = $(this).attr('title') || $(this).text();
                layer.open({
                    type: 8,
                    title: title,
                    area: [width + 'px', height + 'px'],
                    opener: jdiyAdmin.getLocalArea(roots).attr('id'),
                    content: href,
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        layero.find("button[type=submit]").click();
                    }
                });
            });

            roots.find('input.fmt_date').each(function () {
                var that = this,
                    opts = {elem: that, type: 'date'};
                if ($(this).attr('format')) {
                    delete opts.type;
                    opts.format = $(this).attr('format');
                }
                layui.laydate.render(opts);
            });

            roots.find('input.fmt_datetime').each(function () {
                var that = this,
                    opts = {elem: that, type: 'datetime'};
                if ($(this).attr('format')) {
                    delete opts.type;
                    opts.format = $(this).attr('format');
                }
                layui.laydate.render(opts);
            });

          /*  roots.find('input.layui-tree-select').each(function () {
                let tree = layui.tree, oThis = $(this),
                    val = oThis.val(), url = oThis.data('url'), treeOnlyLeaf = !!oThis.attr('treeOnlyLeaf'),
                    treeDisplay = oThis.attr('treeDisplay'),
                    CLASS = 'layui-form-select', TITLE = 'layui-select-title', DISABLED = 'layui-disabled',
                    placeholder = oThis.attr('placeholder') || '', title = oThis.attr('title') || '',
                    treeElemId = "treeselect" + new Date().getTime(),
                    disabled = this.disabled,
                    hasRender = oThis.next('.' + CLASS);
                let reElem = $(['<div class="layui-unselect ' + CLASS
                    , (disabled ? ' layui-select-disabled' : '') + '" id="' + treeElemId + '">'
                    , '<div class="' + TITLE + '">'
                    , ('<input type="text" placeholder="' + placeholder + '" '
                        + ('value="' + (title || '') + '"') //默认值
                        + ' readonly'
                        + ' class="layui-input layui-unselect'
                        + (disabled ? (' ' + DISABLED) : '') + '">') //禁用状态
                    , '<i class="layui-edge"></i></div>'
                    , '<div class="jdiy-tree-select">' +
                    '<div class="tree-close" style="width:100%;height:22px;text-align:center;line-height:25px;color:#999;cursor:pointer;">清除选中</div>' +
                    '<div class="treeDiv"></div></div>'
                    , '</div>'].join(''));
                hasRender[0] && hasRender.remove(); //如果已经渲染，则Rerender
                oThis.after(reElem);
                oThis.hide();

                let inst = layui.tree.render({
                    elem: reElem.find('.jdiy-tree-select .treeDiv'),
                    id: treeElemId, //定义索引
                    jdiyTreeSelectedId: val,//绿底默认选中状态
                    showCheckbox: false, //是否显示复选框
                    showLine: false, //是否开启连接线。默认 true，若设为 false，则节点左侧出现三角图标。
                    accordion: false, //是否开启手风琴模式，默认 false
                    onlyIconControl: !treeOnlyLeaf, //是否仅允许节点左侧图标控制展开收缩。默认 false
                    isJump: false, //是否允许点击节点时弹出新窗口跳转。默认 false
                    data: url,
                    ajaxCallBack: function (d) {
                        let dis = d.msg;
                        if (treeDisplay === 'leaf') dis = dis.substring(dis.lastIndexOf('/') + 1);
                        else if (treeDisplay !== '/') dis = dis.split('/').join(treeDisplay);
                        reElem.find('input').val(dis);
                    },
                    text: {
                        defaultNodeName: '无数据',
                        none: '无数据或者加载失败。'
                    },
                    click: function (obj) {
                        if (!treeOnlyLeaf || !obj.data.lazy && (!obj.data.children || obj.data.children.length < 1)) {
                            reElem.find('.jdiy-tree-select').hide();

                            if (treeDisplay === 'leaf') {
                                $('#' + treeElemId + ' input').val(obj.data.title);
                            } else {
                                let na = [];
                                $(obj.elem).add($(obj.elem).parents('.layui-tree-set')).each(function () {
                                    let t = $(this).children(0).find('.layui-tree-txt');
                                    if (t.length) na.push(t.html());
                                });
                                $('#' + treeElemId + ' input').val(na.join(treeDisplay));
                            }

                            oThis.val(obj.data.id);
                            reElem.find('.layui-this').removeClass('layui-this');
                            $($(obj.elem).children("div").get(0)).addClass('layui-this');
                            oThis.removeClass('layui-form-danger');
                        }
                        // console.log(oThis.val());
                        // console.log(obj.data); //得到当前点击的节点数据
                        // console.log(obj.state); //得到当前节点的展开状态：open、close、normal
                        // console.log(obj.elem); //得到当前节点元素
                        // console.log(obj.data.children); //当前节点下是否有子节点
                    },
                    spread: function (obj) {
                        if (obj.state === 'open') {
                            $.ajax({
                                url: url,
                                data: {parentId: obj.data.id},
                                success: function (d) {
                                    if (d.code === 200) {
                                        tree.lazytree(treeElemId, obj.elem, d.data);
                                    } else {
                                        console.error('动态加载树节点失败。data:' + d + "; ajax_ret:" + d);
                                        tree.lazytree(inst.config.id, obj.elem, []);
                                    }
                                }
                            });
                        }
                    }
                });

                let hide = function (e) {
                    if ($(e.target).hasClass('layui-tree-entry')) {
                        $(e.target).find('.layui-tree-txt').click();//点击树形文字后面的空白区也生效
                    }
                    if ($(e.target).parents('.jdiy-tree-select').length) return;
                    reElem.find('.jdiy-tree-select').hide();
                }
                reElem.find('.tree-close').click(function () {
                    $('#' + treeElemId + ' input').val('');
                    oThis.val('');
                    reElem.find('.jdiy-tree-select').hide();
                });
                if (!disabled) {
                    reElem.find('.' + TITLE).on("click", function (e) {
                        e.stopPropagation();
                        reElem.find('.jdiy-tree-select').toggle();
                    });
                }
                $(document).off('click', hide).on('click', hide); //点击其它元素关闭 select
            });

*/
        };
    exports('jdiyAdmin', {
        init: exec
    });
});